import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { Link } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import ActivityListABI from '../contract/ABIs/ActivityList.json'; // 活动列表合约 ABI
import MaterialListABI from '../contract/ABIs/MaterialList.json'; // 材料列表合约 ABI
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI
import ReviewerListABI from '../contract/ABIs/ReviewerList.json'; // 审核员列表合约 ABI
import AdminListABI from '../contract/ABIs/AdminList.json'; // 管理员列表合约 ABI

import ActivityListAddress from '../contract/ADDRESSes/ActivityListAddress.js'; // 活动列表合约地址
import MaterialListAddress from '../contract/ADDRESSes/MaterialListAddress'; // 材料列表合约地址
import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址
import ReviewerListAddress from '../contract/ADDRESSes/ReviewerListAddress'; // 审核员列表合约地址
import AdminListAddress from '../contract/ADDRESSes/AdminListAddress'; // 管理员列表合约地址
import PointsExchangeAddress from "../contract/ADDRESSes/PointsExchangeAddress.js" // 积分兑换合约地址
import CourseListAddress from '../contract/ADDRESSes/CourseListAddress';//课程列表合约地址
import logosm from '../static/bootstrap/images/logo-sm.svg'

// import '../static/css/app.css'; // 导入 CSS 文件
import $ from 'jquery';
// import '../static/registercss/css/register.css';

const Registercopy = () => {
  const [web3, setWeb3] = useState(null);
  const [contractUserList, setContractUserList] = useState(null);
  const [contractReviewerList, setcontractReviewerList] = useState(null);
  const [contractAdminList, setcontractAdminList] = useState(null);
  const [contractActivityList, setcontractActivityList] = useState(null);
  const [contractMaterialList, setcontractMaterialList] = useState(null);

  const [userName, setUserName] = useState('');
  const [password, setPassword] = useState('');
  const [gender, setGender] = useState(true);
  const [phone, setPhone] = useState('');
  const [reviewerNo, setreviewerNo] = useState('');
  const [adminNo, setAdminNo] = useState('');
  const [role, setRole] = useState('1'); // 默认角色为用户
  const navigate = useNavigate();

  useEffect(() => {
    async function init() {
      // 连接到以太坊网络
      if (window.ethereum) {
        const web3Instance = new Web3(window.ethereum);
        try {
          // 请求用户授权
          await window.ethereum.enable();
          setWeb3(web3Instance);

          // 创建活动列表合约实例
          const activityListInstance = new web3Instance.eth.Contract(
            ActivityListABI,
            ActivityListAddress
          );
          setcontractActivityList(activityListInstance);

          // 创建材料列表合约实例
          const materialListInstance = new web3Instance.eth.Contract(
            MaterialListABI,
            MaterialListAddress
          );
          setcontractMaterialList(materialListInstance);

          // 创建用户列表合约实例
          const userListInstance = new web3Instance.eth.Contract(
            UserListABI,
            UserListAddress
          );
          setContractUserList(userListInstance);

          // 创建审核员列表合约实例
          const reviewerListInstance = new web3Instance.eth.Contract(
            ReviewerListABI,
            ReviewerListAddress
          );
          setcontractReviewerList(reviewerListInstance);

          // 创建管理员列表合约实例
          const adminListInstance = new web3Instance.eth.Contract(
            AdminListABI,
            AdminListAddress
          );
          setcontractAdminList(adminListInstance);

        } catch (error) {
          console.error(error);
        }
      } else {
        console.error('请安装以太坊浏览器插件，如 MetaMask');
      }
    }
    init();
  }, []);


  // 获取用户列表函数
  const fetchDataFromContract = async () => {
    if (contractUserList) {
      try {
        // 调用智能合约的某个函数
        const result = await contractUserList.methods.getUserList().call();
        console.log(result);
      } catch (error) {
        console.error(error);
      }
    }
  };

  // 用户注册函数
  const RegisterUser = async () => {
    if (contractUserList) {
      try {
        // 获取当前用户的以太坊账户地址
        const accounts = await web3.eth.getAccounts();
        const fromAddress = accounts[0];
        console.log("fromAddress:", fromAddress, "Input:", ActivityListAddress, MaterialListAddress, PointsExchangeAddress, userName, password, gender, phone);
        // 调用用户列表合约的 createUser 函数
        await contractUserList.methods.createUser(ActivityListAddress, MaterialListAddress, PointsExchangeAddress, userName, password, gender, phone).send({ from: fromAddress });
        alert('用户注册成功！');
        navigate('/login')
      } catch (error) {
        console.error(error);
        alert('用户注册失败！');
      }
    }
  };
  // 审核员注册函数
  const RegisterReviewer = async () => {
    if (contractReviewerList) {
      try {
        // 获取当前用户的以太坊账户地址
        const accounts = await web3.eth.getAccounts();
        const fromAddress = accounts[0];
        console.log("fromAddress:", fromAddress, "Input:", ActivityListAddress, MaterialListAddress, CourseListAddress, userName, password, phone, reviewerNo);
        // 调用用户列表合约的 createUser 函数
        await contractReviewerList.methods.createReviewer(ActivityListAddress, MaterialListAddress, CourseListAddress, userName, password, phone, reviewerNo).send({ from: fromAddress });
        alert('审核员注册成功！');
        navigate('/login')
      } catch (error) {
        console.error(error);
        alert('审核员注册失败！');
      }
    }
  };

  // 管理员注册函数
  const RegisterAdmin = async () => {
    if (contractAdminList) {
      try {
        // 获取当前用户的以太坊账户地址
        const accounts = await web3.eth.getAccounts();
        const fromAddress = accounts[0];
        console.log("fromAddress:", fromAddress, "Input:", userName, password, adminNo, phone, gender);
        // 调用用户列表合约的 createUser 函数
        await contractAdminList.methods.createAdmin(userName, password, adminNo, phone, gender).send({ from: fromAddress });
        alert('管理员注册成功！');
        navigate('/login')
      } catch (error) {
        console.error(error);
        alert('管理员注册失败！');
      }
    }
  };

  const isUserFormValid = userName && password && phone;
  const isReviewerFormValid = userName && password && phone && reviewerNo;
  const isAdminFormValid = userName && password && phone && adminNo;


  return (
    <div>
      <div className="container" >
        <div className="row justify-content-center">
          <div className="col-xxl-4 col-xl-4 col-lg-5 col-md-6 col-sm-6 col-12">
            <form
              action="#"
              className="my-5"
            >
              <div className="card p-md-4 p-sm-3">
                <div className="login-form">
                  <a
                    className="mb-4 d-flex"
                    href="index.html"
                  >
                    <img
                      alt="Bootstrap Gallery"
                      className="img-fluid login-logo"
                      src={logosm}
                    />
                  </a>
                  <h3 className="mt-5 mb-4">
                    REGISTER
                  </h3>
                  <div className="mb-3">
                    <label className="form-label">
                      你的身份
                    </label>
                    {/* <input
                                            className="form-control"
                                            placeholder="Enter your email"
                                            type="text"
                                        /> */}
                    <select className="form-control" value={role} onChange={(e) => setRole(e.target.value)}
                      style={{ background: '#242627', border: '1px solid #ced4da', borderRadius: '0.25rem' }}>
                      <option value="1">请选择身份</option>
                      <option value="reviewer">审核员</option>
                      <option value="admin">管理员</option>
                    </select>
                  </div>
                  {/* 默认的 */}
                  {role === '1' && (
                    <div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的用户名
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入用户名"
                          type="text"
                          value={userName} onChange={(e) => setUserName(e.target.value)}
                        />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的密码
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入密码"
                          type="password"
                          value={password} onChange={(e) => setPassword(e.target.value)}
                        />
                      </div>

                      <div className="d-flex align-items-center justify-content-between">
                        <div className="form-check m-0">
                          <input
                            className="form-check-input"
                            defaultValue=""
                            id="rememberPassword"
                            type="checkbox"
                          />
                          <label
                            className="form-check-label"
                            htmlFor="rememberPassword"
                          >
                            Remember
                          </label>
                        </div>
                        <a
                          className="text-primary text-decoration-underline"
                          href="forgot-password.html"
                        >
                          Lost									password?
                        </a>
                      </div>
                      <div className="d-grid py-3 mt-3">
                        <button
                          className="btn btn-lg btn-primary"
                          type="button"
                          onClick={RegisterUser} disabled={!isUserFormValid}
                        >
                          REGISTER
                        </button>
                      </div>
                    </div>
                  )}
                  {/* 审核员 */}
                  {role === 'reviewer' && (
                    <div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的用户名
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入用户名"
                          type="text"
                          value={userName} onChange={(e) => setUserName(e.target.value)}
                        />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的密码
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入密码"
                          type="password"
                          value={password} onChange={(e) => setPassword(e.target.value)}
                        />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的电话号码
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入电话号码"
                          type="text"
                          value={phone} onChange={(e) => setPhone(e.target.value)} />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的审核员编号
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入审核员编号"
                          type="text"
                          value={reviewerNo} onChange={(e) => setreviewerNo(e.target.value)} />
                      </div>
                      <div className="d-flex align-items-center justify-content-between">
                        <div className="form-check m-0">
                          <input
                            className="form-check-input"
                            defaultValue=""
                            id="rememberPassword"
                            type="checkbox"
                          />
                          <label
                            className="form-check-label"
                            htmlFor="rememberPassword"
                          >
                            Remember
                          </label>
                        </div>
                        <a
                          className="text-primary text-decoration-underline"
                          href="forgot-password.html"
                        >
                          Lost									password?
                        </a>
                      </div>
                      <div className="d-grid py-3 mt-3">
                        <button
                          className="btn btn-lg btn-primary"
                          type="button"
                          onClick={RegisterReviewer} disabled={!isReviewerFormValid}
                        >
                          REGISTER
                        </button>
                      </div>
                    </div>
                  )}
                  {/* 管理员 */}
                  {role === 'admin' && (
                    <div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的用户名
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入用户名"
                          type="text"
                          value={userName} onChange={(e) => setUserName(e.target.value)}
                        />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的密码
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入密码"
                          type="password"
                          value={password} onChange={(e) => setPassword(e.target.value)}
                        />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的管理员编号
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入管理员编号"
                          type="text"
                          value={adminNo} onChange={(e) => setAdminNo(e.target.value)}
                        />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的电话号码
                        </label>
                        <input
                          className="form-control"
                          placeholder="请输入电话号码"
                          type="text"
                          value={phone} onChange={(e) => setPhone(e.target.value)}
                        />
                      </div>
                      <div className="mb-3">
                        <label className="form-label">
                          你的性别
                        </label>
                        {/* <input
                          className="form-control"
                          placeholder="请输入电话号码"
                          type="text"
                          value={phone} onChange={(e) => setPhone(e.target.value)}
                          /> */}
                        <select className="form-control" value={gender} onChange={(e) => setGender(e.target.value === 'true')}>
                          <option value="true">男</option>
                          <option value="false">女</option>
                        </select>
                      </div>
                      <div className="d-flex align-items-center justify-content-between">
                        <div className="form-check m-0">
                          <input
                            className="form-check-input"
                            defaultValue=""
                            id="rememberPassword"
                            type="checkbox"
                          />
                          <label
                            className="form-check-label"
                            htmlFor="rememberPassword"
                          >
                            Remember
                          </label>
                        </div>
                        <a
                          className="text-primary text-decoration-underline"
                          href="forgot-password.html"
                        >
                          Lost									password?
                        </a>
                      </div>
                      <div className="d-grid py-3 mt-3">
                        <button
                          className="btn btn-lg btn-primary"
                          type="button"
                          onClick={RegisterAdmin} disabled={!isAdminFormValid}
                        >
                          REGISTER
                        </button>
                      </div>
                    </div>
                  )}
                  <div className="text-center py-2">
                    or Login with
                  </div>
                  <div className="btn-group w-100">
                    <button
                      className="btn btn-sm btn-outline-danger"
                      type="button"
                    >
                      Google
                    </button>
                    <button
                      className="btn btn-sm btn-outline-primary"
                      type="button"
                    >
                      Facebook
                    </button>
                    <button
                      className="btn btn-sm btn-outline-info"
                      type="button"
                    >
                      Twitter
                    </button>
                  </div>
                  <div className="text-center pt-4">
                    <span>
                      Not registered?
                    </span>
                    <Link to={`/register`}
                      className="text-primary text-decoration-underline"
                    >
                      没有注册，请注册
                    </Link>
                  </div>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>

    </div>

  );
}

export default Registercopy;